package com.huangfuyi.datamodel.service.impl;

import com.huangfuyi.common.utils.ObjectUtils;
import com.huangfuyi.datamodel.dao.EDataModelInitDao;
import com.huangfuyi.datamodel.entity.EDataModelInitConnectInfo;
import com.huangfuyi.datamodel.exceptions.EDataModelInitException;
import com.huangfuyi.datamodel.service.EDataModelInitService;
import com.huangfuyi.datasource.entity.EConnectConf;
import com.huangfuyi.datasource.enums.EDataSourceType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Locale;

@Service
public class EDataModelInitServiceImpl implements EDataModelInitService {

    private final Logger log = LoggerFactory.getLogger(EDataModelInitServiceImpl.class);

    private final String TAG = "数据模型 > 模块初始化业务 ==> ";

    @Autowired
    private EDataModelInitDao dataModelDao;

    @Override
    public void initDataModel(EDataSourceType dataSourceType, List<EConnectConf> connectInfo) {
        try {
            dataModelDao.initDataSource();
        } catch (Exception e) {
            log.warn("{}使用已保存的数据源信息初始化数据链接失败，原因：{}", TAG, e.getMessage());
        }

        replaceDataSource(dataSourceType, connectInfo);
    }

    @Override
    public void replaceDataSource(EDataSourceType dataSourceType, List<EConnectConf> connectInfo) {
        EDataModelInitConnectInfo initConnectInfoOld = dataModelDao.queryDataModelConnectInfo();

        int connectInfoSavedCount = dataModelDao.saveDataModelConnectInfo(dataSourceType, connectInfo);
        if (connectInfoSavedCount <= 0) {
            throw new EDataModelInitException(String.format(Locale.ROOT, "%s新数据源链接信息保存失败！", TAG));
        }

        EDataModelInitConnectInfo connectInfoSaved = dataModelDao.queryDataModelConnectInfo();
        if (ObjectUtils.isEmpty(connectInfoSaved) || ObjectUtils.isEmpty(connectInfoSaved.getConnectInfos())) {
            throw new EDataModelInitException(String.format(Locale.ROOT, "%s查询已保存的数据源链接信息失败！", TAG));
        }

        try {
            dataModelDao.initDataSource();
        } catch (Exception e) {
            dataModelDao.saveDataModelConnectInfo(initConnectInfoOld.getType(), initConnectInfoOld.getConnectInfos());
            throw new EDataModelInitException(String.format(Locale.ROOT, "%s使用新数据源初始化失败！", TAG));
        }
    }

}
